﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Linq;
using WinDocker.Common.Global;

namespace WinDocker.Common.Helper.WindowsService
{
    /// <summary>
    /// 服务端WebSocket通讯服务
    /// </summary>
    public class ReStartServer
    {
        /// <summary>
        /// 后台服务安装
        /// </summary>
        /// <param name="strPath"></param>
        /// <param name="ServiceName"></param>
        /// <returns></returns>
        public static string SetupService(string strPath, string serviceName = "WinDockerService")
        {
            string strResult = "";
            try
            {
                //string sCmd = @"C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe " + strPath;
                string sCmd = "sc create " + serviceName + " start= delayed-auto binpath= \"" + strPath + "\"";
                string str = Execute(sCmd, 9000);
                Log(sCmd, str, "后台服务安装");
                strResult += (str + "\r\n\r\n");
            }
            catch (Exception ex)
            {
                throw new Exception("SetupServiceError /n" + ex.Message);
            }
            return strResult;
        }

        /// <summary>
        /// 后台服务卸载
        /// </summary>       
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static string UnSetupService(/*string strPath,*/ string serviceName = "WinDockerService")
        {
            string strResult = "";
            try
            {
                //string sCmd = @"C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe -u " + strPath;
                string sCmd = "sc delete " + serviceName;
                string str = Execute(sCmd, 19000);
                Log(sCmd, str, "后台服务卸载");
                strResult += (str + "\r\n\r\n");
            }
            catch (Exception ex)
            {
                throw new Exception("SetupServiceError /n" + ex.Message);
            }
            return strResult;
        }


        /// <summary>
        /// 服务启动
        /// </summary>
        /// <param name="strPath"></param>
        /// <param name="ServiceName"></param>
        /// <returns></returns>
        public static string StartService(string serviceName)
        {
            string strResult = "";
            try
            {
                string sCmd = "Net Start " + serviceName;
                string str = Execute(sCmd, 25000);
                Log(sCmd, str, "服务启动");
                strResult += (str + "\r\n\r\n");
            }
            catch (Exception ex)
            {
                throw new Exception("StartServiceError /n" + ex.Message);
            }
            return strResult;
        }

        /// <summary>
        /// 服务停止
        /// </summary>
        /// <param name="strPath"></param>
        /// <param name="ServiceName"></param>
        /// <returns></returns>
        public static string StopService(string serviceName)
        {
            string strResult = "";
            try
            {
                string sCmd = "Net Stop " + serviceName;
                string str = Execute(sCmd, 25000);
                Log(sCmd, str, "服务停止");
                strResult += (str + "\r\n\r\n");
            }
            catch (Exception ex)
            {
                throw new Exception("StartServiceError /n" + ex.Message);
            }
            return strResult;
        }
        //wmic service where name='WinDockerService' get name
        /// <summary>
        /// 判断服务是否存在
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static bool JudgeService(string serviceName)
        {
            try
            {
                string sCmd = "wmic service where name='" + serviceName + "' get name";
                string str = Execute(sCmd, 5000);
                Log(sCmd, str, "判断服务是否存在");
                return str.IndexOf(serviceName) >= 0;
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer JudgeService Err:" + ex.Message);
            }
            return false;
        }
        //wmic service where (state="running" and  name="WinDockerService" )  get name
        /// <summary>
        /// 判断服务是否在运行
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static bool JudgeServiceRun(string serviceName)
        {
            try
            {
                string sCmd = "wmic service where (state=\"running\" and name = \"" + serviceName + "\" )  get name";
                string str = Execute(sCmd, 5000);
                Log(sCmd, str, "判断服务是否在运行");
                return str.IndexOf(serviceName) >= 0;
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer JudgeServiceRun Err:" + ex.Message);
            }
            return false;
        }

        private static void Log(string sCmd, string sRet, string strDescript = "")
        {
            try
            {
                string strLog = "\r\n【命令描述】 = " + strDescript;
                strLog += ("\r\n【命令请求】 = " + sCmd);
                strLog += ("\r\n【命令应答】 = " + sRet);
                strLog += ("\r\n");
                LogWrite.TxtExport_DateNow("LogService.txt", strLog);
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer Log Err:" + ex.Message);
            }
        }

        /// <summary>  
        /// 执行DOS命令，返回DOS命令的输出  
        /// </summary>  
        /// <param name="dosCommand">dos命令</param>  
        /// <param name="milliseconds">等待命令执行的时间（单位：毫秒），  
        /// 如果设定为0，则无限等待</param>  
        /// <returns>返回DOS命令的输出</returns>  
        private static string Execute(string command, int seconds)
        {
            return Execute(command, seconds, out Process _Process);
        }

        /// <summary>  
        /// 执行DOS命令，返回DOS命令的输出 0 
        /// </summary>  
        /// <param name="dosCommand">dos命令</param>  
        /// <param name="milliseconds">等待命令执行的时间（单位：毫秒），  
        /// 如果设定为0，则无限等待</param>  
        /// <param name="_Process">返回的进程对象</param> 
        /// <returns>返回DOS命令的输出</returns>  
        public static string Execute(string command, int seconds, out Process _Process)
        {
            _Process = null;
            string output = ""; //输出字符串  
            try
            {
                if (command != null && !command.Equals(""))
                {
                    var fn = "cmd.exe";
                    var wd = "";
                    var cmdWd = Configs.GetAndAdd("CmdWorkingDirectory", "_").Trim();
                    if (cmdWd != "_")
                    {
                        fn = $"{cmdWd}\\{fn}";
                        wd = cmdWd;
                        command = (command ?? "").Trim();
                        if (command.IndexOf("wmic") == 0)
                        {
                            command = $"{cmdWd}\\wbem\\{command}";
                        }
                        else
                        {
                            command = $"{cmdWd}\\{command}";
                        }
                    }

                    Process process = new Process();//创建进程对象  
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.FileName = fn;//"cmd.exe";//设定需要执行的命令  
                    startInfo.WorkingDirectory = wd;//2024-05-21
                    startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出  
                    startInfo.UseShellExecute = false;//不使用系统外壳程序启动  
                    startInfo.RedirectStandardInput = false;//不重定向输入  
                    startInfo.RedirectStandardOutput = true; //重定向输出  
                                                             //startInfo.RedirectStandardError = true; // 重定向错误输出  //? 2024-05-21
                    startInfo.CreateNoWindow = true;//不创建窗口
                                                    //LogWrite.TxtExport_DateNow("LogTest.txt", $"D:{startInfo.WorkingDirectory}");

                    process.StartInfo = startInfo;
                    _Process = process;
                    try
                    {
                        if (process.Start())//开始进程  
                        {
                            if (seconds == 0)
                            {
                                process.WaitForExit();//这里无限等待进程结束  
                            }
                            else
                            {
                                process.WaitForExit(seconds); //等待进程结束，等待时间为指定的毫秒  
                            }
                            output = process.StandardOutput.ReadToEnd();//读取进程的输出  
                        }
                    }
                    catch (Exception ex)
                    {
                        LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer Execute 0Err:" + ex.Message);
                    }
                    finally
                    {
                        if (process != null)
                            process.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer Execute Err:" + ex.Message);
            }
            return output;
        }

        #region Old

        //private static string ServerName = "CyzFaceService7";


        //public ReStartServer()
        //{ }

        ///// <summary>
        ///// 安装服务
        ///// </summary>
        ///// <param name="filepath">服务全路径名</param>
        //public static bool InstallService(string filepath)
        //{
        //    try
        //    {
        //        IDictionary stateSaver = new Hashtable();
        //        System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(ServerName);
        //        if (!ServiceIsExisted())
        //        {
        //            //安装服务
        //            AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
        //            myAssemblyInstaller.UseNewContext = true;
        //            myAssemblyInstaller.Path = filepath;
        //            myAssemblyInstaller.Install(stateSaver);
        //            myAssemblyInstaller.Commit(stateSaver);
        //            myAssemblyInstaller.Dispose();

        //            //启动服务
        //            //service.Start();
        //        }
        //        //else
        //        //{
        //        //    if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
        //        //    {
        //        //        service.Start();
        //        //    }
        //        //}
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        //throw new Exception("installServiceError /n" + ex.Message);
        //    }
        //    return false;
        //}

        ///// <summary>
        ///// 卸载STForeignService 服务
        ///// </summary>
        ///// <param name="filepath"></param>
        //public static bool UnInstallService(string filepath)
        //{
        //    try
        //    {
        //        if (ServiceIsExisted())
        //        {
        //            //卸载服务   
        //            AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
        //            myAssemblyInstaller.UseNewContext = true;
        //            myAssemblyInstaller.Path = filepath;
        //            myAssemblyInstaller.Uninstall(null);
        //            myAssemblyInstaller.Dispose();
        //            return true;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        //throw new Exception("unInstallServiceError /n" + ex.Message);
        //    }
        //    return false;
        //}

        ///// <summary>
        ///// 判断STForeignService服务是否存在
        ///// </summary>
        ///// <returns></returns>
        //public static bool ServiceIsExisted()
        //{
        //    ServiceController[] services = ServiceController.GetServices();
        //    foreach (ServiceController s in services)
        //    {

        //        if (s.ServiceName == ServerName)
        //        {
        //            return true;
        //        }
        //    }
        //    return false;
        //}

        ///// <summary>
        ///// 重启STForeignService服务
        ///// </summary>
        ///// <returns></returns>
        //public static bool ReStartSTForeignService()
        //{
        //    bool bReturn = false;
        //    try
        //    {
        //        //取得服务名
        //        ServiceController service = new ServiceController(ServerName);
        //        //判断是否在运行
        //        if (service.Status == ServiceControllerStatus.Running)
        //        {
        //            //停止其服务
        //            service.Stop();
        //            service.WaitForStatus(ServiceControllerStatus.Stopped);
        //        }
        //        //重启其服务
        //        service.Start();
        //        service.WaitForStatus(ServiceControllerStatus.Running);

        //        bReturn = true;
        //    }
        //    catch
        //    { }

        //    return bReturn;
        //}


        ///// <summary>
        ///// 判断STForeignService 服务是否正在运行
        ///// </summary>
        ///// <returns></returns>
        //public static bool ServiceIsRuning()
        //{
        //    bool bReturn = false;
        //    try
        //    {

        //        ServiceController service = new ServiceController(ServerName);
        //        if (service.Status == ServiceControllerStatus.Running)
        //        {
        //            bReturn = true;
        //        }

        //    }
        //    catch
        //    { }

        //    return bReturn;

        //}


        ///// <summary>   
        ///// 启动STForeignService服务   
        ///// </summary>   
        ///// <returns></returns>   
        //public static bool ServiceStart()
        //{
        //    try
        //    {
        //        ServiceController service = new ServiceController(ServerName);
        //        if (service.Status == ServiceControllerStatus.Running)
        //        {
        //            return true;
        //        }
        //        else
        //        {
        //            //设置超时时间
        //            TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 20);
        //            service.Start();
        //            service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        //        }
        //    }
        //    catch
        //    {
        //        return false;
        //    }
        //    return true;

        //}

        ///// <summary>   
        ///// 停止STForeignService服务   
        ///// </summary>   
        ///// <returns></returns>   
        //public static bool ServiceStop()
        //{
        //    try
        //    {
        //        ServiceController service = new ServiceController(ServerName);
        //        if (service.Status == ServiceControllerStatus.Stopped)
        //        {
        //            return true;
        //        }
        //        else
        //        {
        //            //TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 20);
        //            service.Stop();
        //            //service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        //        }
        //        return true;
        //    }
        //    catch
        //    {
        //        //return false;
        //    }
        //    return false;
        //}


        ///// <summary>   
        ///// 修改服务的启动项 2为自动,3为手动   
        ///// </summary>   
        ///// <param name="startType"></param>   
        ///// <param name="serviceName"></param>   
        ///// <returns></returns>   
        //public static bool ChangeServiceStartType(int startType)
        //{
        //    try
        //    {
        //        RegistryKey regist = Registry.LocalMachine;
        //        RegistryKey sysReg = regist.OpenSubKey("SYSTEM");
        //        RegistryKey currentControlSet = sysReg.OpenSubKey("CurrentControlSet");
        //        RegistryKey services = currentControlSet.OpenSubKey("Services");
        //        RegistryKey servicesName = services.OpenSubKey(ServerName, true);
        //        servicesName.SetValue("Start", startType);
        //    }
        //    catch (Exception ex)
        //    {

        //        return false;
        //    }
        //    return true;


        //}

        #endregion Old

        ///// <summary>
        ///// 寄生WebAPI对像
        ///// </summary>
        //private static HttpSelfHostServer server;

        ///// <summary>
        ///// WebAPI启动(REST API处理开始)
        ///// </summary>
        ///// <param name="pURL">启动的URL（如: http://localhost:6925/ ）</param>
        ///// <returns></returns>
        //public static bool RESTAPIServiceStart(string pURL)
        //{
        //    try
        //    {
        //        if (server != null)
        //        {
        //            return false;
        //        }
        //        var config = new HttpSelfHostConfiguration(pURL);
        //        config.MaxReceivedMessageSize = 10 * 65536;//后台服务 接收第三方系统一次请求的最大数据量默认为655360字节既0.625M字节
        //        try
        //        {
        //            long lMaxReceivedMessageSize = 0;
        //            float f = float.Parse(Tool.GetAndAddConfig("HttpMaxReceivedMessageSize", "0.625"));
        //            lMaxReceivedMessageSize = (long)(f * 1024 * 1024);
        //            config.MaxReceivedMessageSize = lMaxReceivedMessageSize;
        //        }
        //        catch { }
        //        config.Routes.MapHttpRoute("API Default", "API/{controller}/{id}", new { id = RouteParameter.Optional });
        //        server = new HttpSelfHostServer(config);
        //        server.OpenAsync().Wait(System.Threading.CancellationToken.None);
        //        return true;

        //    }
        //    catch (Exception ex)
        //    {
        //        pURL = ex.Message.ToString();
        //        LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer RESTAPIServiceStart出错:" + ex.Message.ToString());
        //    }
        //    return false;
        //}

        ///// <summary>
        ///// WebAPI停止(REST API处理结束)
        ///// </summary>
        ///// <returns></returns>
        //public static bool RESTAPIServiceStop()
        //{
        //    try
        //    {
        //        if (server != null)
        //        {
        //            server.CloseAsync().Wait(System.Threading.CancellationToken.None);
        //            System.Threading.Thread.Sleep(888);
        //            server.Dispose();
        //            server = null;
        //            return true;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer RESTAPIServiceStop出错:" + ex.Message.ToString());
        //    }
        //    return false;
        //}

        //private static WebSocketServer webServer;
        //private static List<IWebSocketConnection> allSockets = new List<IWebSocketConnection>();

        ///// <summary>
        ///// WebSocket服务监听启动
        ///// </summary>
        ///// <param name="webSocketListenPort">WebSocket服务监听端口</param>
        //public static void WebSocketStart(string webSocketListenPort)
        //{
        //    try
        //    {
        //        if (!GlobalParameters.IsWebSocketPush)
        //        {
        //            return;
        //        }

        //        allSockets.Clear();
        //        webServer = new WebSocketServer("ws://0.0.0.0:" + webSocketListenPort);
        //        webServer.Start((socket) =>
        //        {
        //            try
        //            {
        //                socket.OnOpen = () =>
        //                {
        //                    try
        //                    {
        //                        allSockets.Add(socket);
        //                        LogWrite.TxtExport_DateNow("LogTrace.txt", "【WebSocket】" + socket.ConnectionInfo.Id.ToString() + " Open!");
        //                        //this.ShowMsg(socket.ConnectionInfo.Id.ToString() + " Open!");
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer WebSocketStart[内1]出错:" + ex.Message.ToString());
        //                    }
        //                };
        //                socket.OnClose = () =>
        //                {
        //                    try
        //                    {
        //                        allSockets.Remove(socket);
        //                        LogWrite.TxtExport_DateNow("LogTrace.txt", "【WebSocket】" + socket.ConnectionInfo.Id.ToString() + " Close!");
        //                        //this.ShowMsg(socket.ConnectionInfo.Id.ToString() + " Close!");
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer WebSocketStart[内2]出错:" + ex.Message.ToString());
        //                    }
        //                };
        //                socket.OnMessage = (message) =>
        //                {
        //                    try
        //                    {
        //                        if (GlobalParameters.WebSocketReceiveEvent != null)
        //                        {
        //                            try
        //                            {

        //                                object[] paraArray = new object[] { socket, message };

        //                                GlobalParameters.WebSocketReceiveEvent(paraArray, null);
        //                            }
        //                            catch (Exception ex)
        //                            {
        //                                LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer WebSocketStart[内05]出错:" + ex.Message.ToString());
        //                            }
        //                        }
        //                        //allSockets.ToList().ForEach(s => s.Send("nd_Echo:" + message));
        //                        //this.ShowMsg(socket.ConnectionInfo.Id.ToString() + " Recevice:" + message);
        //                        string strMsg = (message ?? "").Trim();
        //                        if (strMsg.IndexOf("♂〓♀") >= 0)//注:对从客户端发送上来的数据进行广播转发
        //                        {
        //                            string strMsg2 = strMsg.Replace("♂〓♀", "");
        //                            System.Threading.Thread th = new System.Threading.Thread((obj) =>
        //                            {
        //                                try
        //                                {
        //                                    string strMsg2Tmp = (string)obj;
        //                                    WebSocketSend(strMsg2Tmp);
        //                                }
        //                                catch (Exception ex)
        //                                {
        //                                    LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer WebSocketStart[内5]出错:" + ex.Message.ToString());
        //                                }
        //                            });
        //                            th.Start(strMsg2);
        //                        }
        //                        LogWrite.TxtExport_DateNow("LogTrace.txt", "【WebSocket】" + socket.ConnectionInfo.Id.ToString() + " Recevice:" + message);
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer WebSocketStart[内3]出错:" + ex.Message.ToString());
        //                    }
        //                };

        //            }
        //            catch (Exception ex)
        //            {
        //                LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer WebSocketStart[内0]出错:" + ex.Message.ToString());
        //            }
        //        });

        //    }
        //    catch (Exception ex)
        //    {
        //        LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer WebSocketStart出错:" + ex.Message.ToString());
        //    }
        //}
        ///// <summary>
        ///// WebSocket服务监听停止
        ///// </summary>
        //public static void WebSocketStop()
        //{
        //    try
        //    {

        //        foreach (var socket in allSockets.ToList())
        //        {
        //            try
        //            {
        //                socket.Close();
        //            }
        //            catch (Exception ex)
        //            {
        //                LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer WebSocketStop[内]出错:" + ex.Message.ToString());
        //            }
        //        }
        //        webServer.Dispose();
        //        webServer = null;
        //        allSockets.Clear();
        //    }
        //    catch (Exception ex)
        //    {
        //        LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer WebSocketStop出错:" + ex.Message.ToString());
        //    }
        //}

        ///// <summary>
        ///// WebSocket处理锁对像
        ///// </summary>
        //private readonly static object objLockWebSocket = new object();

        ///// <summary>
        ///// 向连接上来的所有WebSocket对像发送数据
        ///// </summary>
        ///// <param name="strSend">发送的内容</param>
        //public static void WebSocketSend(string strSend)
        //{
        //    lock (objLockWebSocket)
        //    {
        //        try
        //        {
        //            foreach (var socket in allSockets.ToList())
        //            {
        //                try
        //                {
        //                    //socket.Send(strSend);
        //                    List<object> ltPararmer = new List<object>();
        //                    ltPararmer.Add(socket);
        //                    ltPararmer.Add(strSend);
        //                    (new WebSocketSendClass()).Start(ltPararmer);
        //                }
        //                catch (Exception ex)
        //                {
        //                    LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer WebSocketSend[内]出错:" + ex.Message.ToString());
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer WebSocketSend出错:" + ex.Message.ToString());
        //        }
        //    }
        //}

        ///// <summary>
        ///// 向连接上来的某个WebSocket对像发送数据
        ///// </summary>
        ///// <param name="obj">IWebSocketConnection对像(需拆箱)</param>
        ///// <param name="strSend">发送的内容</param>
        //public static void WebSocketSend(object obj, string strSend)
        //{
        //    try
        //    {
        //        IWebSocketConnection sock = (IWebSocketConnection)obj;
        //        sock.Send(strSend);
        //    }
        //    catch (Exception ex)
        //    {
        //        LogWrite.TxtExport_DateNow("LogErr.txt", "ReStartServer WebSocketSend[2]出错:" + ex.Message.ToString());
        //    }
        //}

    }
}
